package com.jsh.erp.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.mappers.ProjectMapper;
import com.jsh.erp.datasource.mappers.QuoteProjectMapper;
import com.jsh.erp.datasource.vo.TreeNode;
import com.jsh.erp.service.project.ProjectService;
import com.jsh.erp.service.qoute.QuoteService;
import com.jsh.erp.service.systemConfig.SystemConfigService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.service.userBusiness.UserBusinessService;
import com.jsh.erp.utils.BaseResponseInfo;
import com.jsh.erp.utils.ErpInfo;
import com.jsh.erp.utils.ExcelUtils;
import com.jsh.erp.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

import static com.jsh.erp.utils.ResponseJsonUtil.returnJson;

/**
 */
@RestController
@RequestMapping(value = "/quote")
@Api(tags = {"报价单管理"})
public class QuoteController {
    private Logger logger = LoggerFactory.getLogger(QuoteController.class);
    @Resource
    private QuoteService quoteService;
    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private QuoteProjectMapper quoteProjectMapper;


    @GetMapping("/category/tree")
    public Object findCategoryTree() {
        JSONArray tree = quoteService.buildCategoryTree(-1);
        return tree;
    }

    @GetMapping("/category/info")
    public Object getCategoryInfo(
            @RequestParam(value = "id", required = true) Long id
    ){
        QuoteCategory quoteCategory = quoteService.categoryGetInfo(id);
        return  quoteCategory;
    }

    @PostMapping("/category/delete")
    public String deleteCategory(@RequestBody JSONObject requestParams){
        String id = requestParams.getString("id");

        List<QuoteCategory> categoryList = quoteService.findCategoryByParentId(Long.parseLong(id));
        if ( categoryList.size() > 0 ){
            return returnJson(Maps.newHashMap(), "不能删除包含子类型的数据", ErpInfo.ERROR.code);
        }
        Map<String,Object> data = Maps.newHashMap();
        int count = quoteService.categoryDelete(id);
        data.put("count", count);
        if(count > 0) {
            return returnJson(data, ErpInfo.OK.name, ErpInfo.OK.code);
        } else {
            return returnJson(data, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
        }
    }

    @PostMapping("/category/edit")
    public String editCategory(@RequestBody JSONObject requestParams,
                               HttpServletRequest request) {
        Long id = requestParams.getLong("id");
        String name = requestParams.getString("name");
        String remark = requestParams.getString("remark");
        int sort = requestParams.getIntValue("sort");
        Long parentId = requestParams.getLong("parentId");

        Map<String,Object> data = Maps.newHashMap();
        int count = 0;
        if ( id == null ){
            count = quoteService.categoryAdd(name,parentId,remark,sort);
        }else{
            count = quoteService.categoryEdit(id,name,parentId,remark,sort);
        }

        if(count > 0) {
            return returnJson(data, ErpInfo.OK.name, ErpInfo.OK.code);
        } else {
            return returnJson(data, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
        }

    }

    @GetMapping("/template/table")
    public BaseResponseInfo templateTable(
            @RequestParam("currentPage") Integer currentPage,
            @RequestParam("pageSize") Integer pageSize,
            @RequestParam(value = "quoteCategoryId") String quoteCategoryId,
            @RequestParam(value = "name", required = false) String name
    ){
        BaseResponseInfo res = new BaseResponseInfo();
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            List<QuoteTemplate> quoteTemplates = quoteService.quoteTemplates(Long.parseLong(quoteCategoryId), name);

            // 计算起始和结束索引
            int total = quoteTemplates.size();
            int startIndex = (currentPage - 1) * pageSize;
            int endIndex = Math.min(startIndex + pageSize, total);

            // 检查索引是否有效
            if (startIndex >= total) {
                map.put("rows", Collections.emptyList());
            } else {
                map.put("rows", quoteTemplates.subList(startIndex, endIndex));
            }

            map.put("total", quoteTemplates.size());
            res.code = 200;
            res.data = map;
        } catch (NumberFormatException e) {
            res.code = 500;
            res.data = "获取数据失败";
        }
        return res;
    }

    @GetMapping("/template/list")
    public BaseResponseInfo templateList(
            @RequestParam(value = "quoteCategoryId") String quoteCategoryId
    ){
        BaseResponseInfo res = new BaseResponseInfo();
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            List<QuoteTemplate> quoteTemplates = quoteService.quoteTemplates(Long.parseLong(quoteCategoryId), "");

            map.put("list", quoteTemplates);
            res.code = 200;
            res.data = map;
        } catch (NumberFormatException e) {
            res.code = 500;
            res.data = "获取数据失败";
        }
        return res;
    }

    @PostMapping("/template/edit")
    public String templateCategory(@RequestBody JSONObject requestParams,
                               HttpServletRequest request) {
        Long id = requestParams.getLong("id");
        String name = requestParams.getString("name");
        String quoteCategoryId = requestParams.getString("quoteCategoryId");
        String remark = requestParams.getString("remark");

        Map<String,Object> data = Maps.newHashMap();
        int count = 0;
        if ( id == null ){
            count = quoteService.templateAdd(name,quoteCategoryId,remark);
        }else{
            count = quoteService.templateEdit(id,name,quoteCategoryId,remark);
        }

        if(count > 0) {
            return returnJson(data, ErpInfo.OK.name, ErpInfo.OK.code);
        } else {
            return returnJson(data, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
        }
    }

    @PostMapping("/template/delete")
    public String deleteTemplate(@RequestBody JSONObject requestParams){
        String id = requestParams.getString("id");

        Map<String,Object> data = Maps.newHashMap();
        int count = quoteService.templateDelete(id);
        data.put("count", count);
        if(count > 0) {
            return returnJson(data, ErpInfo.OK.name, ErpInfo.OK.code);
        } else {
            return returnJson(data, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
        }
    }

    @GetMapping("/template/item/list")
    public BaseResponseInfo templateItemList(
            @RequestParam(value = "quoteTemplateId") String quoteTemplateId
    ){
        BaseResponseInfo res = new BaseResponseInfo();
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            List<QuoteTemplateItem> quoteTemplateItems = quoteService.quoteTemplateItemsByTemplateId(Long.parseLong(quoteTemplateId));

            map.put("list", quoteTemplateItems);
            res.code = 200;
            res.data = map;
        } catch (NumberFormatException e) {
            res.code = 500;
            res.data = "获取数据失败";
        }
        return res;
    }

    @PostMapping("/template/item/edit")
    public BaseResponseInfo templateItemEdit(@RequestBody JSONObject requestParams){
        String id = requestParams.getString("id");
        String count = requestParams.getString("count");
        int i = quoteService.templateItemEdit(Long.parseLong(id), Long.parseLong(count));
        BaseResponseInfo res = new BaseResponseInfo();
        res.code = 200;
        res.data = i ;
        return res;
    }

    @PostMapping("/template/item/delete")
    public BaseResponseInfo templateItemDelete(@RequestBody JSONObject requestParams){
        String id = requestParams.getString("id");
        int i = quoteService.templateItemDelete(Long.parseLong(id));
        BaseResponseInfo res = new BaseResponseInfo();
        res.code = 200;
        res.data = i ;
        return res;
    }

    @PostMapping("/template/item/add")
    public BaseResponseInfo templateItemAdd(@RequestBody JSONObject requestParams){
        String quoteTemplateId = requestParams.getString("quoteTemplateId");
        String materialId = requestParams.getString("materialId");
        int i = quoteService.templateItemAdd(Long.parseLong(quoteTemplateId), Long.parseLong(materialId));
        BaseResponseInfo res = new BaseResponseInfo();
        res.code = 200;
        res.data = i ;
        return res;
    }

    @GetMapping("/project/list")
    public BaseResponseInfo projectList(
            @RequestParam(value = "projectId") String projectId
    ){
        BaseResponseInfo res = new BaseResponseInfo();
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            List<QuoteProject> quoteProjects = quoteService.quoteList(Long.parseLong(projectId));

            map.put("list", quoteProjects);
            res.code = 200;
            res.data = map;
        } catch (NumberFormatException e) {
            res.code = 500;
            res.data = "获取数据失败";
        }
        return res;
    }

    @PostMapping("/project/add")
    public BaseResponseInfo projectAdd(@RequestBody JSONObject requestParams){
        String projectId = requestParams.getString("projectId");
        String name = requestParams.getString("name");
        String remark = requestParams.getString("remark");
        int i = quoteService.projectAdd(projectId, name, remark);
        BaseResponseInfo res = new BaseResponseInfo();
        res.code = 200;
        res.data = i ;
        return res;
    }

    @PostMapping("/project/edit")
    public BaseResponseInfo projectEdit(@RequestBody JSONObject requestParams){
        String id = requestParams.getString("id");
        String name = requestParams.getString("name");
        String remark = requestParams.getString("remark");
        int i = quoteService.projectEdit(Long.parseLong(id), name, remark);
        BaseResponseInfo res = new BaseResponseInfo();
        res.code = 200;
        res.data = i ;
        return res;
    }

    @PostMapping("/project/copy")
    public BaseResponseInfo projectCopy(@RequestBody JSONObject requestParams){
        String id = requestParams.getString("id");
        BaseResponseInfo res = new BaseResponseInfo();
        try {
            quoteService.projectCopy(Long.parseLong(id));
            res.code = 200;
            res.data = new JSONObject().fluentPut("message","复制成功") ;
        } catch (NumberFormatException e) {
            res.code = 500;
            res.data = new JSONObject().fluentPut("message","复制报价单时出错:"+e.getMessage()) ;
        }

        return res;
    }

    @GetMapping("/project/export")
    public void projectExport(String quoteProjectId,HttpServletRequest request, HttpServletResponse response){
        try {

            QuoteProject quoteProject = quoteProjectMapper.selectByPrimaryKey(Long.parseLong(quoteProjectId));
            Project project = projectMapper.selectByPrimaryKey(quoteProject.getProjectId());
            List<QuoteProjectItem> quoteProjectItems = quoteService.projectItemsByQuoteProjectId(Long.parseLong(quoteProjectId));


            String title = quoteProject.getName();

            String[] titles = {
                    "类别", "名称", "单位", "单价", "数量",
                    "制造商", "规格型号", "材质", "标准", "尺寸",
                    "抛光要求", "连接形式", "温度", "压力", "密封要求",
                    "长度", "其他技术参数", "条码", "编码"
            };
            List<String[]> objects = new ArrayList<String[]>();
            if (null != quoteProjectItems) {
                for (QuoteProjectItem quoteProjectItem : quoteProjectItems) {
                    MaterialVo4Unit m = quoteProjectItem.getMaterialInfo();
                    String[] objs = new String[20];
                    objs[0] = m.getCategoryName();
                    objs[1] = m.getName();
                    objs[2] = m.getUnitName();
                    objs[3] = String.valueOf(m.getWholesaleDecimal());
                    objs[4] = String.valueOf(quoteProjectItem.getCount());
                    objs[5] = m.getMfrs();
                    objs[6] = m.getModel();
                    objs[7] = m.getCaizhi();
                    objs[8] = m.getBiaozhun();
                    objs[9] = m.getOtherField1();
                    objs[10] = m.getPaoguangdu();
                    objs[11] = m.getLianjie();
                    objs[12] = m.getOtherField2();
                    objs[13] = m.getOtherField3();
                    objs[14] = m.getMopian();
                    objs[15] = m.getChangdu();
                    objs[16] = m.getStandard();
                    objs[17] = m.getmBarCode();
                    objs[18] = m.getFullBarCode();
                    objects.add(objs);
                }
            }

            File file = ExcelUtils.exportObjectsWithoutTitle(title, "*该文件包含机密数据，切勿外发", titles, title, objects);
            ExcelUtils.downloadExcel(file, file.getName(), response);

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @PostMapping("/project/delete")
    public BaseResponseInfo projectDelete(@RequestBody JSONObject requestParams){
        String id = requestParams.getString("id");
        BaseResponseInfo res = new BaseResponseInfo();
        List<QuoteProjectItem> quoteProjectItems = quoteService.projectItemsByQuoteProjectId(Long.parseLong(id));
        if ( quoteProjectItems.size() > 0 ){
            res.code = 500;
            res.data = new JSONObject().fluentPut("message","不能删除包含报价子条目的报价单") ;
        }else{
            int i = quoteService.projectDelete(Long.parseLong(id));
            res.code = 200;
            res.data = i ;
        }
        return res;
    }

    @GetMapping("/project/subsystem/list")
    public BaseResponseInfo projectSubsystemList(
            @RequestParam(value = "quoteProjectId") String quoteProjectId
    ){
        BaseResponseInfo res = new BaseResponseInfo();
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            List<QuoteProjectSubsystem> quoteProjectSubsystemList = quoteService.projectSubsystemList(Long.parseLong(quoteProjectId));

            map.put("list", quoteProjectSubsystemList);
            res.code = 200;
            res.data = map;
        } catch (NumberFormatException e) {
            res.code = 500;
            res.data = "获取数据失败";
        }
        return res;
    }

    @PostMapping("/project/item/add")
    public BaseResponseInfo projectItemAdd(@RequestBody JSONObject requestParams){
        String quoteProjectId = requestParams.getString("quoteProjectId");
        String materialId = requestParams.getString("materialId");
        int i = quoteService.projectItemAdd(Long.parseLong(quoteProjectId), Long.parseLong(materialId));
        BaseResponseInfo res = new BaseResponseInfo();
        res.code = 200;
        res.data = i ;
        return res;
    }

    @GetMapping("/project/item/list")
    public BaseResponseInfo projectItemList(
            @RequestParam(value = "quoteProjectId") String quoteProjectId
    ){
        BaseResponseInfo res = new BaseResponseInfo();
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            List<QuoteProjectItem> quoteProjectItems = quoteService.projectItemsByQuoteProjectId(Long.parseLong(quoteProjectId));

            map.put("list", quoteProjectItems);
            res.code = 200;
            res.data = map;
        } catch (NumberFormatException e) {
            res.code = 500;
            res.data = "获取数据失败";
        }
        return res;
    }

    @PostMapping("/project/item/edit")
    public BaseResponseInfo projectItemEdit(@RequestBody JSONObject requestParams){
        String id = requestParams.getString("id");
        String count = requestParams.getString("count");
        String remark = requestParams.getString("remark");
        int i = quoteService.projectItemEdit(Long.parseLong(id), Long.parseLong(count),remark);
        BaseResponseInfo res = new BaseResponseInfo();
        res.code = 200;
        res.data = i ;
        return res;
    }

    @PostMapping("/project/item/delete")
    public BaseResponseInfo projectItemDelete(@RequestBody JSONObject requestParams){
        String id = requestParams.getString("id");
        int i = quoteService.projectItemDelete(id);
        BaseResponseInfo res = new BaseResponseInfo();
        res.code = 200;
        res.data = i ;
        return res;
    }

    @PostMapping("/project/item/import")
    public BaseResponseInfo projectItemImport(@RequestBody JSONObject requestParams){
        String quoteProjectId = requestParams.getString("quoteProjectId");
        String quoteTemplateId = requestParams.getString("quoteTemplateId");
        int i = quoteService.projectItemImport(Long.parseLong(quoteProjectId), Long.parseLong(quoteTemplateId));
        BaseResponseInfo res = new BaseResponseInfo();
        res.code = 200;
        res.data = i ;
        return res;
    }
}
